class MyBlockingQueue{
    private String[] elems=null;
    private int head=0;
    private int tail=0;
    private int size=0;
    public MyBlockingQueue(int capacity){
        elems=new String[capacity];
    }
    void  put(String elem) throws InterruptedException {
        synchronized (this){
            while (size>=elems.length){
                //后续处理队列满,阻塞的情况
                this.wait();
            }
            elems[tail]=elem;
            tail++;
            if(tail>=elems.length){
                //到达末尾,就回到开头
                tail=0;
            }
            //更新size 的值
            size++;
            //唤醒下面阻塞的wait()
            this.notify();

        }

    }
    String take() throws InterruptedException {
        synchronized (this){
            while (size==0){
                //队列空的,后续处理阻塞的情况
                this.wait();
            }
            //取出head指向的元素
            String result=elems[head];
            head++;
            if(head>=elems.length){
                head=0;
            }
            size--;
            //take一个元素,就唤醒上面put中的wait操作
            this.notify();
            return result;

        }

    }
}
public class demo31 {
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue(100);
        Thread t1 = new Thread(()->{
            try {
                int count =0;
                while (true){
                    myBlockingQueue.put(count+"");
                    System.out.println("生产"+count);
                    count++;
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }

        });
        Thread t2= new Thread(()->{
            try {
                while (true){
                    String result = myBlockingQueue.take();
                    System.out.println("消费"+result);
                    Thread.sleep(1000);
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }

        });
        t1.start();
        t2.start();
    }
}
